package global

import (
	"fmt"
	log "code.google.com/p/log4go"
	"github.com/toolkits/file"
	"encoding/json"
	"errors"
)

/**
	获取配置
 */
func Config() *ConfigGlobal {
	configLock.RLock()
	defer configLock.RUnlock()
	return config
}
/**
	解析配置
 */
func ParseConfig(cfg string) {
	if cfg == "" {
		errStr := fmt.Sprintf("use -c to init specify configuration file")
		log.Info(errStr)
		PanicError(errors.New(errStr),nil)
	}
	if !file.IsExist(cfg) {
		errStr := fmt.Sprintf("config file: %s is not existent",cfg)
		log.Info(errStr)
		PanicError(errors.New(errStr),nil)
	}
	ConfigFile = cfg
	configContent, err := file.ToTrimString(cfg)
	if err != nil {
		errStr := fmt.Sprintf("read config file: %s fail: %s",cfg,err)
		log.Info(errStr)
		PanicError(errors.New(errStr),nil)
	}
	var c ConfigGlobal
	err = json.Unmarshal([]byte(configContent), &c)
	if err != nil {
		errStr := fmt.Sprintf("parse config file: %s fail: %s",cfg, err)
		log.Info(errStr)
		PanicError(errors.New(errStr),nil)
	}
	configLock.Lock()
	defer configLock.Unlock()
	config = &c
	log.Info("read config file: %s successfully",cfg)
}